package com.yupi.springbootinit.service.impl;
import java.util.ArrayList;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.orders.OrderCreateRequest;
import com.yupi.springbootinit.model.entity.Orders;
import com.yupi.springbootinit.model.entity.Product;
import com.yupi.springbootinit.model.vo.OrdersVO;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.service.OrdersService;
import com.yupi.springbootinit.mapper.OrdersMapper;
import com.yupi.springbootinit.service.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Transactional(rollbackFor = Exception.class) //开启事务回滚
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{

    @Resource
    private ProductService productService;

    /**
     * 创建订单
     * @param orderCreateRequest
     * @param loginUser
     * @return
     */
    @Override
    public Long crateOrder(OrderCreateRequest orderCreateRequest, UserVO loginUser) {
        Long userId = loginUser.getId();
        if(userId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //商品id不为空
        Long productId = orderCreateRequest.getProductId();
        if(productId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"无商品id");
        }

        String address = loginUser.getAddress();
        if(StringUtils.isBlank(address)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"地址为空");
        }

        //将对应的未售商品改为已售
//        LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(Product::getId,productId).set(Product::getProductStatus,1);
//        boolean result = productService.update(updateWrapper);
//        if(!result){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR,"更新商品状态失败");
//        }

        //根据商品id查询出商品名称
        Product product = productService.getById(productId);
        Long id = product.getUserId();
        if(userId.equals(id)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不能购买自己创建的商品");
        }
        if(product == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //商品名称
        String productName = product.getProductName();
        //商品描述
        String context = product.getContext();
        //商品单价
        BigDecimal price = product.getPrice();


        Orders orders = new Orders();
        orders.setProductId(productId);
        orders.setUserId(userId);
        orders.setPrice(price);
        orders.setAddress(address);
        orders.setContext(context);
        orders.setProductName(productName);

        //插入数据到订单表
        boolean result2 = this.save(orders);
        if(!result2){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"创建订单失败");
        }

        return orders.getId();
    }

    /**
     * 查询我创建的订单
     * @param loginUser
     * @return
     */
    @Override
    public List<OrdersVO> queryMyOrders(UserVO loginUser) {
        Long userId = loginUser.getId();
        if(userId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //根据用当前登录id查询出订单
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        List<Orders> ordersList = this.list(queryWrapper);
        List<Long> productIdList = ordersList.stream().map(Orders::getProductId).collect(Collectors.toList());


        //查询出商品的图片
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.in("id",productIdList);
        List<Product> productList = productService.list(productQueryWrapper);
        //取出产品图片
        List<String> photoList = productList.stream().map(Product::getProductPhoto).collect(Collectors.toList());

        //放进队列方便脱敏
        Queue<String> queue = new LinkedList<>();
        for (String photo : photoList) {
            queue.add(photo);
        }
        //脱敏处理
        List<OrdersVO> ordersVOList = new ArrayList<>();
        for(Orders orders : ordersList){
            OrdersVO ordersVO = new OrdersVO();
            BeanUtils.copyProperties(orders,ordersVO);
            ordersVO.setProductPhoto(queue.poll());
            ordersVOList.add(ordersVO);
        }

        return ordersVOList;
    }


}




